/**
 * Created by TomSean on 2017/4/14.
 */
var PermitTypeManager = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}

PermitTypeManager.prototype = {
    init : function() {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent.find(".search-panel"));
        var functionArray = [
            {fName : 'search_btn', fs : this.findData},
            {fName : 'reset_btn', fs : this.resetInfo}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#search_permit_type'), parentModelKey:BASIS.TRAFFIC_TYPE_CLASS.ROOT}, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#search_enable'), parentModelKey:BASIS.DATA_STATUS.ROOT}, this);
        this.initTable();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
    },
    initTable : function() {
        var _this = this;
        var columns = [
            {
                width:30,
                headerTemplate : '<input type="checkbox" gridId="traffic_permit_type_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="id" value="${id}">'
            },
            {
                title : '类型编号',
                field : 'accessCode'
            },
            {
                title : '类型名称',
                field : 'accessName'
            },
            {
                title : '类型状态',
                template : '#:Utils.getModelNameByParentKey(BASIS.DATA_STATUS.ROOT, isEnable)#'
            },
            {
                title : '创建时间',
                field : 'createTime'
            },
            {
                title : '创建人',
                field : 'createUserid'
            }
        ];
        _this.sysUtils.createGird(
            _this.$parent.find('#traffic_permit_type_data_list'),
            {
                selectable : 'single',
                autoSync : true,
                columnMenu : true,
                pageable : {input : true, numeric : false},
                columns : columns,
                change : function() {
                    var selected = $.map(this.select(), function(itm) {
                        return $(itm).find("input[type=checkbox]").val();
                    });
                    _this.selectRowId = selected[0];
                }
            });
    },
    findData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var grid = _this.$parent.find('#traffic_permit_type_data_list').data('kendoGrid');
        var params = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        var dataSource = _this.sysUtils.getDataSource({
            url : baseApiPath + 'traffic_permit_type/list',
            data : {'curdatetime':new Date().getTime(), 'jsonParam':JSON.stringify(params)},
            dataType : 'odata'
        });
        grid.setDataSource(dataSource);
    },
    openEditWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var id = _this.selectRowId;
        if (isEmpty(id)) {
            notification({title : '警告' , message : '请先选择需要编辑的数据'}, 'info');
            return;
        }
        _this.isEdit = true;
        JsonpAjax(baseApiPath + 'traffic_permit_type/get/'+id, undefined, 'json', function(res) {
            _this.entity = res;
            _this.openWindow('编辑通行证类型');
        }, true);
    },
    openNewWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = false;
        _this.openWindow('新建通行证类型');
    },
    openWindow : function(title) {
        this.editDiv = this.sysUtils.openWindow(this.editDiv, {
            title : title,
            height : '450px',
            width : '800px',
            resizable : false,
            content : 'views/parkLotCenter/parkingLotInfo/passTypeEdit.html'
        }, true);
    }
};

var PermitTypeEdit = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
};
PermitTypeEdit.prototype = {
    init : function() {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'save_info', fs : this.saveInfo },
            {fName : 'cancel', fs : function() { $('#' + permitType.editDiv).data('kendoWindow').close(); } }
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#type_class'), parentModelKey:BASIS.TRAFFIC_TYPE_CLASS.ROOT}, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#type_status'), parentModelKey:BASIS.DATA_STATUS.ROOT}, this);
        JsonpAjax(baseApiPath + 'traffic_permit_type/charge_info/list', undefined, 'json', function(res) {
            var charge_info = _this.$parent.find('#charge_info').kendoDropDownList({
                dataTextField: "name",
                dataValueField: "code",
                dataSource: res,
                change : function (e) {
                    var dataItem = this.dataItem();
                    _this.$parent.find('#payMoney').html(this.dataItem().payMoney);
                }
            }).data('kendoDropDownList');
            charge_info.select(0);
            _this.$parent.find('#payMoney').html(charge_info.dataItem().payMoney);
            if (permitType.isEdit == true) {
                _this.loadInfo();
            }
        }, true);
        this.loadTree();
    },
    loadInfo : function() {
        var entity = permitType.entity;
        this.sysUtils.setBindFieldValue(entity);
        this.codeStr = entity.accessChannelCode;
        var charge_info = this.$parent.find('#charge_info').data('kendoDropDownList');
        var payMoney = charge_info.dataItem().payMoney;
        this.$parent.find('#payMoney').val(payMoney);
        permitType.entity = undefined;
        permitType.isEdit = false;
    },
    saveInfo : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (validityForm(_this.$parent)) {
            var treeObj = $.fn.zTree.getZTreeObj("permit_tree");
            var nodes = treeObj.getCheckedNodes(true);
            var ids = '';
            for (var i = 0; i < nodes.length; i++) {
                if ( nodes[i].type.indexOf('chn_') != -1 ){
                    ids += nodes[i].code+',';
                }
            }
            if (!isEmpty(ids)) {
                ids = ids.substring(0, ids.length - 1);
            }
            var dataT = {permits : ids, permitType : JSON.stringify(_this.sysUtils.getBindDocJson())};
            JsonpAjax(baseApiPath + 'traffic_permit_type/save', JSON.stringify(dataT), 'json', function(res) {
                $('#' + permitType.editDiv).data('kendoWindow').close();
                permitType.findData();
            }, true);
        }
    },
    loadTree:function () {
        var _this = this;
        var setting = {
            view: {
                showLine: true,
                selectedMulti: false,
                dblClickExpand: false,
                showIcon: false
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "code",
                    pIdKey: "pid",
                    rootPId: ""
                }
            },
            async: {
                enable: true,
                type:"post",
                url: baseApiPath + "traffic_permit_type/channel/tree",
            },
            check : {
                enable: true,
                autoCheckTrigger: true,
                chkStyle: "checkbox",
                chkboxType: { "Y": "ps", "N": "ps" }
            },
            callback : {
                onAsyncSuccess : function() {
                    var treeObj = $.fn.zTree.getZTreeObj("permit_tree");
                    treeObj.expandAll(true);
                    var codes = !isEmpty(_this.codeStr) ? _this.codeStr.split(',') : '';
                    if ( codes.length > 0 ){
                        var nodes = treeObj.getNodes();
                        for (var i = 0; i < nodes.length; i++) {
                            if (nodes[i].code == codes[i]) {
                                treeObj.checkNode(nodes[i], true, true);
                            }
                            if ( nodes[i].children instanceof Array && nodes[i].children.length > 0) {
                                _this.pdCheck(nodes[i].children, codes, treeObj);
                            }
                        }
                    }
                }
            }
        };
        var t = this.$parent.find("#permit_tree");
        t = $.fn.zTree.init(t, setting);
    },
    pdCheck : function (nodes, codes, treeObj) {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].code == codes[i]) {
                treeObj.checkNode(nodes[i], true, true);
            }
            if ( nodes[i].children instanceof Array && nodes[i].children.length > 0) {
                this.pdCheck(nodes[i].children, codes, treeObj);
            }
        }
    }
};